<template>
    <div>
        <!-- 查询表单 -->
        <el-row :gutter="15" class="query-row">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-input v-model="actSearchForm.name" placeholder="标题" clearable />
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-input v-model="actSearchForm.type" placeholder="类型" clearable />
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-input v-model="actSearchForm.publisher" placeholder="发布人" clearable />
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-date-picker v-model="actSearchForm.begin" type="date" placeholder="发布起始时间" style="width: 100%" />
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-date-picker v-model="actSearchForm.end" type="date" placeholder="发布截至时间" style="width: 100%" />
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <el-button type="primary" icon="el-icon-search" @click="submitSearchAct"
                    class="query-button">搜索</el-button>
            </el-col>
        </el-row>

        <!-- 活动表格 -->
        <el-table :data="actData" border style="width: 100%" class="data-table"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="标题" width="180">
            </el-table-column>
            <el-table-column prop="publisher" label="发布人" width="180">
            </el-table-column>
            <el-table-column prop="createTime" label="发布日期" width="180">
            </el-table-column>
            <el-table-column prop="type" label="类型" width="180">
            </el-table-column>
            <el-table-column prop="updateTime" label="最后操作时间" width="180">
            </el-table-column>
            <el-table-column label="操作" width="120">
                <template v-slot="{ row }">
                    <el-button type="text" size="small" @click="openActEdit(row)" class="edit-btn">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="action-bar">
            <el-pagination class="pagination" :current-page="pagination.current" :page-sizes="[5, 10, 20, 50]"
                :page-size="pagination.size" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="actSizeChange" @current-change="actCurrentChange" />
            <div class="action-buttons">
                <el-button type="danger" @click="deleteSelectedActs"
                    :disabled="selectedIds.length === 0">删除选中</el-button>
                <el-button type="primary" @click="actEditDialogVisible = true" class="publish-btn">发布活动</el-button>
            </div>
        </div>
        <el-dialog title="活动发布" :visible.sync="actEditDialogVisible" width="55%">
            <el-form ref="form" :model="actEditForm" :rules="rules" label-width="100px">
                <!-- 基础信息 -->
                <div class="form-section">
                    <el-form-item label="标题" prop="name" required>
                        <el-input v-model="actEditForm.name" placeholder="请输入文章标题（不超过50字）" maxlength="50"
                            show-word-limit></el-input>
                    </el-form-item>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="发布人" prop="publisher" required>
                                <el-input v-model="actEditForm.publisher" placeholder="请输入发布人姓名"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="文章类型" prop="type" required>
                                <el-select v-model="actEditForm.type" placeholder="请选择文章类型" style="width: 100%">
                                    <el-option label="公告" value="公告"></el-option>
                                    <el-option label="校级活动" value="校级活动"></el-option>
                                    <el-option label="普通活动" value="普通活动"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <!-- 内容编辑区 -->
                <div class="editor-section">
                    <div v-for="(item, index) in 6" :key="index" class="content-block">
                        <h3 class="content-title">内容段落 {{ index + 1 }}</h3>
                        <el-form-item :prop="`content${index + 1}`">
                            <el-input type="textarea" :rows="4" resize="vertical"
                                v-model="actEditForm[`content${index + 1}`]" placeholder="请输入段落内容（建议200-500字）"
                                class="rich-textarea"></el-input>
                        </el-form-item>

                        <!-- 图片上传组件（每个段落都能上传） -->
                        <div class="image-uploader">
                            <el-upload :action="null" :http-request="(file) => uploadImage(file, `image${index + 1}`)"
                                :limit="1" list-type="picture-card"
                                :class="{ 'hidden-upload': actEditForm[`image${index + 1}`] }">
                                <i class="el-icon-plus"></i>
                                <div slot="tip" class="upload-tip">
                                    插入图片 {{ index + 1 }}（建议尺寸 1200×600px）
                                </div>
                            </el-upload>
                        </div>
                    </div>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="actEditDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="actEditFormSubmit">立即发布</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import axios from 'axios';
import dayjs from 'dayjs';
import service from '../utils/request'

export default {
    data() {
        return {
            //发送到后端的活动查询条件
            actSearchForm: {
                name: '',
                publisher: '',
                type: '',
                begin: '',
                end: ''
            },
            selectedIds: [],

            //接收后端传回的活动数据
            pagination: {
                current: 1,
                size: 5,
                total: 0
            },
            actData: [],


            //活动编辑
            actEditDialogVisible: false,
            actEditForm: {
                name: '',
                publisher: '',
                type: '',
                content1: '',
                content2: '',
                content3: '',
                content4: '',
                content5: '',
                content6: '',
                image1: '',
                image2: '',
                image3: '',
                image4: '',
                image5: '',
                image6: '',
            },
            
            rules: {
                name: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
                ],
                publisher: [
                    { required: true, message: '请输入发布人', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择文章类型', trigger: 'change' }
                ]
            },
        }

    },
    created() {
        console.log(this.$store)
    },
    mounted() {
        this.submitSearchAct();
    },
    methods: {
        async submitSearchAct() {
            try {
                const param = {
                    ...this.actSearchForm,
                    begin: this.actSearchForm.begin ? dayjs(this.actSearchForm.begin).format("YYYY-MM-DD") : undefined,
                    end: this.actSearchForm.end ? dayjs(this.actSearchForm.end).format("YYYY-MM-DD") : undefined,
                    page: this.pagination.current,
                    pageSize: this.pagination.size
                };
                const res = await service.get('/Act/ActList', { params: param });
                    this.actData = res.rows;
                    this.pagination.total = res.total;
            } catch (error) {
                this.$message.error('查询失败');
            }

        },

        // 图片上传
        async uploadImage(file, fieldName) {
            const formData = new FormData();
            formData.append('image', file.file);
            try {
                const res = await axios.post('/Act/ImgUpload', formData);
                this.actEditForm[fieldName] = res.data.url;
            } catch (error) {
                this.$message.error('上传失败');
            }
        },
        async actEditFormSubmit() {
            try {
                await this.$refs.form.validate();
                const param = this.actEditForm
                const actRes = await axios.post('http://localhost:8080/Act/ActPublish', param);
                if (actRes.data.code == 1) {
                    this.$message.success('发布成功');
                    this.actEditDialogVisible = false;
                    this.submitSearchAct();
                }
            } catch (error) {
                if (error !== 'validation') {
                    this.$message.error('发布失败')
                }
            }

        },
        // 分页大小变化
        actSizeChange(size) {
            this.pagination.size = size;
            this.submitSearchAct();
        },
        // 当前页码变化
        actCurrentChange(current) {
            this.pagination.current = current;
            this.submitSearchAct();
        },
        openActEdit(row) {
            this.actEditDialogVisible = true;
            this.actEditForm = {
                ...row
            }
        },
        handleSelectionChange(selection) {
            this.selectedIds = selection.map(item => item.id)
        },

        // 新增删除选中方法
        async deleteSelectedActs() {
            try {
                await this.$confirm('确定删除选中项吗？', '提示', {
                    type: 'warning'
                })
                const res = await service.post('http://localhost:8080/Act/DeleteById',this.selectedIds,{
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                if (res.code == 1) {
                    this.$message.success('删除成功')
                    this.submitSearchAct()
                }
            } catch (error) {
        if(error !== 'cancel') {
            this.$message.error('删除失败')
        }
    }
        },


    }
}
</script>

<style scoped>
/* 优化查询栏布局 */
.query-row {
    margin-bottom: 20px;
}

.query-row .el-col {
    margin-bottom: 15px;
}

.query-button {
    width: 100%;
}

/* 表格样式优化 */
.data-table {
    margin: 20px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 操作按钮样式 */
.edit-btn {
    padding: 4px 8px;
    color: #409EFF;
}

/* 底部操作栏 */
.action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
}

.action-buttons {
    display: flex;
    gap: 12px;
}

.publish-btn {
    min-width: 120px;
}

/* 响应式优化 */
@media (max-width: 768px) {
    .action-bar {
        flex-direction: column;
        gap: 16px;
    }

    .action-buttons {
        width: 100%;
        justify-content: space-between;
    }

    .pagination {
        margin-bottom: 16px;
    }
}
</style>